import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';

import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:quiver/strings.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import '../../../generated/l10n.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class UdtTbWorkreportrecordQrscanBanJinList extends StatefulWidget {
  UdtTbWorkreportrecordQrscanBanJinList();

  @override
  _UdtTbWorkreportrecordQrscanBanJinListState createState() =>
      _UdtTbWorkreportrecordQrscanBanJinListState();
}

class _UdtTbWorkreportrecordQrscanBanJinListState
    extends State<UdtTbWorkreportrecordQrscanBanJinList> {
  late UdtTbWorkreportrecord udtTbWorkreportrecord = UdtTbWorkreportrecord();

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  //班次
  late List<SelectOptionVO> shiftList = [];
  //报工人员
  late List<SelectOptionVO> reportworkerList = [];
  //工序
  late List<SelectOptionVO> pathList = [];

  Map routeRemarkMap = {};

  // List orderRuleList = [];

  // List userCodeList = [];

  List<UdtTbWorkreportrecord> udtTbWorkreportrecordList = [];
  List<UdtTbWorkreportrecord> dataList = [];
  UdtTbWorkreportrecord workreportrecord = UdtTbWorkreportrecord();

  // Map keyMap = {};

  ValueNotifier<num> total = ValueNotifier<num>(0);

  late var _subscription;

  num area = 0;

  @override
  void initState() {
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "workreportrecordQrscan")
        .listen(_onEnvent);
    super.initState();
    _loadSelectVO();
  }

  @override
  void dispose() {
    StoreUtil.write("key", "workreportrecord");
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码后的结果
  void _onEnvent(dynamic obj) async {
    obj = obj["scan"];
    if (obj.contains("|")) {
      // 合单
      List objList = obj.split("|");
      var falg = await _getData(type: 3, barcode: objList[1]);
      if (falg != null) {
        return;
      }
      List orderList = objList[0].split(";");
      for (var i = 0; i < orderList.length; i++) {
        await _getData(
          type: 1,
          barcode: orderList[i],
        );
      }
      // if (obj.contains(";")) {
      //   List orderList = objList[0].split(";");
      //   for (var i = 0; i < orderList.length; i++) {
      //     await _getData(
      //         type: 1,
      //         barcode: orderList[i],
      //     );
      //   }
      // } else {
      //   await _getData(type: 1, barcode: objList[0]);
      // }
      await _getDataList();
    } else {
      // 人员码
      await _getData(type: 2, barcode: obj.toString());
    }
  }

  _loadSelectVO() async {
    shiftList = [];
    var res = await DynamicDataApi.getModels(model: 'base.shift');
    var starttime;
    var endtime;
    var index = 0;
    if (res.success!) {
      for (var i = 0; i < res.data.length; i++) {
        shiftList.add(SelectOptionVO(
            value: res.data[i]["id"].toString(),
            label: res.data[i]["shiftname"]));
        if (res.data[i]["shiftcode"] == "1001") {
          index = i;
          starttime = DateTime.parse(
              Utils.getDate() + " " + res.data[i]["starttime"] + ":00");
          endtime = DateTime.parse(
              Utils.getDate() + " " + res.data[i]["endtime"] + ":00");
        }
      }
    }
    if (!DateTime.now().isBefore(starttime) &&
        DateTime.now().isBefore(endtime)) {
      udtTbWorkreportrecord.shiftId = res.data[index]["id"].toString();
    } else {
      udtTbWorkreportrecord.shiftId =
          res.data[index == 0 ? 1 : 0]["id"].toString();
    }
    // orderRuleList = (await DynamicDataApi.dictionaryList("orderrule")).data;
    // userCodeList = (await DynamicDataApi.dictionaryList("usercode")).data;
    _loadData();
  }

  _loadData() {
    Map map = StoreUtil.read(Constant.KEY_PRODUCTIONSTATION);
    udtTbWorkreportrecord.stationId = map["stationId"].toString();
    udtTbWorkreportrecord.stationCode = map["stationCode"].toString();
    udtTbWorkreportrecord.stationName = map["stationName"].toString();
    udtTbWorkreportrecord.factoryId = map["factoryId"].toString();
    udtTbWorkreportrecord.factoryName = map["factoryName"].toString();
    udtTbWorkreportrecord.workshopId = map["workshopId"].toString();
    udtTbWorkreportrecord.workshopName = map["workshopName"].toString();
    udtTbWorkreportrecord.teamId = map["teamId"].toString();
    udtTbWorkreportrecord.teamCode = map["teamCode"].toString();
    udtTbWorkreportrecord.teamName = map["teamName"].toString();
    udtTbWorkreportrecord.qualifiedquantity = 0;
    udtTbWorkreportrecord.unqualifiedquantity = 0;
    udtTbWorkreportrecord.repairquantity = 0;
    udtTbWorkreportrecord.cutting = 0;
    udtTbWorkreportrecord.replacenumber = 0;
    reportworkerList = StoreUtil.read(Constant.KEY_REPORTWORKERLIST);
    if(reportworkerList.length == 1){
      udtTbWorkreportrecord.reportworkerId = pathList[0].value.toString();
      udtTbWorkreportrecord.reportworkerName = pathList[0].label.toString();
    }
    setState(() {});
  }

  // bool _isOrder(String barcode) {
  //   for (var value in orderRuleList) {
  //     if(barcode.startsWith(value["dictionarycode"])){
  //       return true;
  //     }
  //   }
  //   return false;
  // }
  //
  // bool _isUser(String barcode) {
  //   for (var value in userCodeList) {
  //     if(barcode.startsWith(value["dictionarycode"])){
  //       return true;
  //     }
  //   }
  //   return false;
  // }

  int _getUserIndex(String id) {
    for (var i = 0; i < reportworkerList.length; i++) {
      if (id == reportworkerList[i].value) {
        return i;
      }
    }
    return -1;
  }

  _getTotal() {
    total.value = 0;
    dataList.forEach((element) {
      total.value += element.qualifiedquantity!;
    });
  }

  _getData({int? type, String? barcode}) async {
    // todo type代表不同的对象（1：生产单号；2：人员；3：产品；）
    if (isBlank(barcode)) {
      return;
    }
    try {
      if (type == 1) {
        // todo 产品单号
        // if(isBlank(udtTbWorkreportrecord.productCode)){
        //   CryUtils.message("请先绑定产品信息");
        //   return ;
        // }
        // if(barcode == udtTbWorkreportrecord.productionorderno){
        //   CryUtils.message("已经绑定过该订单，请重新扫描");
        //   return ;
        // }
        num planQTY = 0;
        if(barcode!.contains("CJBHD")){
          var res = await DynamicDataApi.getModels(
            model: 'product.stockorder',
            key: 'stockorderno',
            val: barcode
          );
          if (!res.success! || res.data.length == 0) {
            CryUtils.message("$barcode生产单号不存在！");
            return;
          }
          planQTY = res.data[0]["orderqty"];
          // 用有用的第一个生产单号获得工序即可
            if (pathList.length == 0) {
            if(StoreUtil.hasData(Constant.KEY_PATHLIST)){
              StoreUtil.read(Constant.KEY_PATHLIST).forEach((element) {
                pathList.add(element);
              });
            }
            if (pathList.length == 1) {
              udtTbWorkreportrecord.processId = pathList[0].value.toString();
            }
          }
        }else{
          var res = await HttpUtil.get(
              "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanInfo?PlanId=$barcode");
          if (!res.success! || res.data.length == 0) {
            CryUtils.message("$barcode生产单号不存在！");
            return;
          }
          udtTbWorkreportrecord.productionType = res.data[0]["ProductionType"];
          planQTY = _getPlanQTY(
              res.data[0]["PlanItems"], udtTbWorkreportrecord.productCode!);
          if (planQTY == -1) {
            CryUtils.message(
                "$barcode生产单号下没有${udtTbWorkreportrecord.productName}产品！");
            return;
          }
          // 用有用的第一个生产单号获得工序即可
          if (pathList.length == 0) {
            var res1 = await HttpUtil.get(
                "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanRouteInfo?PlanId=$barcode&ProductSpec=${udtTbWorkreportrecord.productCode}");
            if (!res1.success! || res1.data.length == 0) {
              CryUtils.message("找不到对应工序！");
              return;
            }
            List list = res1.data[0]["PlanRoutes"][0]["RouteDatas"];
            print(res1.data[0]["PlanRoutes"][0]["RouteDatas"]);
            for (var i = 0; i < list.length; i++) {
              if (udtTbWorkreportrecord.teamCode == list[i]["OperGroup"]) {
                var res = await DynamicDataApi.getModels(
                    model: "mrp.routing.workcenter",
                    key: "note",
                    val: list[i]["OperId"]);
                if (res.success!) {
                  pathList.add(SelectOptionVO(
                      label: list[i]["OperName"],
                      value: res.data[0]["id"].toString()));
                  routeRemarkMap[res.data[0]["id"].toString()] = list[i]["Remark"];
                }
              }
            }
            if (pathList.length == 1) {
              udtTbWorkreportrecord.processId = pathList[0].value.toString();
            }
            if(StoreUtil.hasData(Constant.KEY_PATHLIST)){
              StoreUtil.read(Constant.KEY_PATHLIST).forEach((element) {
                pathList.add(element);
              });
            }
          }
        }


        // formKey.currentState!.save();
        // 添加合格数
        udtTbWorkreportrecord.qualifiedquantity = planQTY;
        // 添加生产单号
        udtTbWorkreportrecord.productionorderno = barcode;
        // keyMap[barcode] = udtTbWorkreportrecordList.length;
        udtTbWorkreportrecordList.add(udtTbWorkreportrecord.copyWith());
        // if(isLast!){
        //   setState(() {});
        //   _getTotal();
        // }
        return;
      }
      if (type == 2) {
        // todo 人员
        ResponseBodyApi res = await DynamicDataApi.getModels(
            model: "res.users", key: 'login', val: barcode);
        if (res.success!) {
          if (res.data.length == 0) {
            CryUtils.message("该人员不存在");
            return;
          } else if (res.data.length > 1) {
            CryUtils.message("编号重复");
            return;
          } else {
            var index = _getUserIndex(res.data[0]["id"].toString());
            if (index == -1) {
              CryUtils.message("该人员不属于${udtTbWorkreportrecord.teamName}");
              return;
            }
            formKey.currentState!.save();
            udtTbWorkreportrecord.reportworkerId =
                res.data[0]["id"] != false ? res.data[0]["id"].toString() : "";
            udtTbWorkreportrecord.reportworkerName =
                reportworkerList[index].label.toString();
            setState(() {});
          }
        }
        return;
      }
      if (type == 3) {
        if(udtTbWorkreportrecord.teamCode == 'PTPFA'
         ||udtTbWorkreportrecord.teamCode == 'PTPFB'
         ||udtTbWorkreportrecord.teamCode == 'PTPFC'){
          var res = await HttpUtil.get("http://10.1.13.100/mesapi/ztkd/CommonData/GetMetalParams?PartCodes=['$barcode']");
          if(res.success!){
            area = res.data[0]['SprayArea'];
          }
        }
        // 生成对应的产品信息
        await StockQuantOdooApi.HWRequest("product_check",barcode);
        ResponseBodyApi res = await DynamicDataApi.getModels(
            model: "product.template", key: 'default_code', val: barcode);
        if (res.success!) {
          if (res.data.length == 0) {
            CryUtils.message("$barcode零件图号不存在");
            // _clearProductCode();
            return "";
          } else if (res.data.length > 1) {
            CryUtils.message("$barcode零件图号重复");
            // _clearProductCode();
            return "";
          } else {
            formKey.currentState!.save();
            // if (barcode == udtTbWorkreportrecord.productCode) {
            //   return "";
            // }
            udtTbWorkreportrecordList = [];
            dataList = [];
            // udtTbWorkreportrecord.productionorderno = null;
            pathList = [];
            udtTbWorkreportrecord.processId = null;
            udtTbWorkreportrecord.productId =
                res.data[0]["id"] != false ? res.data[0]["id"].toString() : "";
            udtTbWorkreportrecord.productCode =
                res.data[0]["default_code"] != false
                    ? res.data[0]["default_code"].toString()
                    : "";
            udtTbWorkreportrecord.productName = res.data[0]["name"] != false
                ? res.data[0]["name"].toString()
                : "";
            udtTbWorkreportrecord.spec = res.data[0]["description"] != false
                ? res.data[0]["description"].toString()
                : "";
            setState(() {});
          }
        }
      }
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return "";
    }
  }

  _reset() {
    var reportworkerId = udtTbWorkreportrecord.reportworkerId;
    var reportworkerName = udtTbWorkreportrecord.reportworkerName;
    pathList = [];
    udtTbWorkreportrecordList = [];
    dataList = [];
    total.value = 0;
    udtTbWorkreportrecord = UdtTbWorkreportrecord();
    udtTbWorkreportrecord.reportworkerId = reportworkerId;
    udtTbWorkreportrecord.reportworkerName = reportworkerName;
    _loadSelectVO();
    // setState(() {});
  }

  _getDataList() async {
    dataList = [];
    if (!isBlank(udtTbWorkreportrecord.processId)) {
      var routeRemark = "";
      if(routeRemarkMap.containsKey(udtTbWorkreportrecord.processId) &&
        !isBlank(routeRemarkMap[udtTbWorkreportrecord.processId])
      ){
        routeRemark = routeRemarkMap[udtTbWorkreportrecord.processId];
      }
      ResponseBodyApi res = await DynamicDataApi.getModels(
          model: "product.workreportrecord",
          key: "product_id",
          val: int.parse(udtTbWorkreportrecord.productId!),
          key2: "process_id",
          val2: int.parse(udtTbWorkreportrecord.processId!));
      if (res.success!) {
        Map map = {};
        // 整理相同单号的数量
        for (var i = 0; i < res.data.length; i++) {
          var key = res.data[i]["productionorderno"];
          var val = res.data[i]["qualifiedquantity"];
          if (map.containsKey(key)) {
            map[key] += val;
          } else {
            map[key] = val;
          }
        }
        for (var i = 0; i < udtTbWorkreportrecordList.length; i++) {
          UdtTbWorkreportrecord workreportrecordCopy = udtTbWorkreportrecordList[i].copyWith();
          // bool flag = true;
          if (map.containsKey(workreportrecordCopy.productionorderno)) {
            var qualifiedquantity =
                workreportrecordCopy.qualifiedquantity! -
                    map[workreportrecordCopy.productionorderno];
            if (qualifiedquantity <= 0) {
              // flag = false;
              workreportrecordCopy.qualifiedquantity = 0;
            } else {
              workreportrecordCopy.qualifiedquantity =
                  qualifiedquantity;
            }
          }
          workreportrecordCopy.planQty = workreportrecordCopy.qualifiedquantity;
          workreportrecordCopy.routeRemark = routeRemark;
          // if (flag) {
          dataList.add(workreportrecordCopy);
          // }
        }
        if (dataList.length == 0) {
          CryUtils.message("该工序下的单子已全部报工完成，请扫码其他单子或选择其他工序");
          dataList = [];
        }
        _getTotal();
        setState(() {});
      }
    } else {
      CryUtils.message("请选择工序");
      setState(() {});
    }
  }

  num _getPlanQTY(List list, String productCode) {
    for (var element in list) {
      if (element["ProductSpec"] == productCode) {
        return element["PlanQTY"];
      }
    }
    return -1;
  }

  _clearProductCode() {
    setState(() {
      udtTbWorkreportrecord.productId = null;
      udtTbWorkreportrecord.productCode = null;
      udtTbWorkreportrecord.productName = null;
      udtTbWorkreportrecord.spec = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    var rows = this.dataList.map((workreportrecord) {
      var result = DataRow(cells: [
        DataCell(Text(workreportrecord.productionorderno.toString())),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.qualifiedquantity,
          onChange: (v) {
            formKey.currentState?.save();
            _getTotal();
          },
          onSaved: (v) {
            workreportrecord.qualifiedquantity = v;
          },
          // validator: (v) {
          //   return v!.isEmpty ? S.of(context).required : null;
          // }
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.unqualifiedquantity,
          onSaved: (v) {
            workreportrecord.unqualifiedquantity = v;
          },
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.repairquantity,
          onSaved: (v) {
            workreportrecord.repairquantity = v;
          },
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.cutting,
          onSaved: (v) {
            workreportrecord.cutting = v;
          },
        )),
        DataCell(CryInputNum(
          width: 80,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.replacenumber,
          onSaved: (v) {
            workreportrecord.replacenumber = v;
          },
        )),
        DataCell(CryInput(
          width: 150,
          padding: 0,
          contentPadding: 0,
          value: workreportrecord.remark,
          onSaved: (v) {
            workreportrecord.remark = v;
          },
        )),
      ]);
      return result;
    }).toList();
    if (rows.length != 0) {
      rows.add(DataRow(cells: [
        DataCell(Text("合计")),
        // DataCell(Text(total.value.toString())),
        DataCell(ValueListenableBuilder<num>(
          valueListenable: total,
          builder: (context, value, child) {
            return Text(value.toString());
          },
        )),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
        DataCell(Container()),
      ]));
    }
    var table = DataTable(
      columns: [
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text("合格数量")),
        DataColumn(label: Text("不合格数量")),
        DataColumn(label: Text("备货数量")),
        DataColumn(label: Text("刀数")),
        DataColumn(label: Text("换模个数")),
        DataColumn(label: Text("备注")),
      ],
      rows: rows,
    );
    var form = Form(
      key: formKey,
      child: Column(
        children: <Widget>[
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                CrySelect(
                  width: 130,
                  label: '班次',
                  value: udtTbWorkreportrecord.shiftId,
                  dataList: shiftList,
                  onSaved: (v) {
                    udtTbWorkreportrecord.shiftId = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CrySelect(
                  width: 200,
                  label: '生产工序',
                  dataList: pathList,
                  value: udtTbWorkreportrecord.processId,
                  onChange: (v) async {
                    if (udtTbWorkreportrecord.processId != v) {
                      udtTbWorkreportrecord.processId = v;
                      _getDataList();
                    }
                  },
                  onSaved: (v) {
                    udtTbWorkreportrecord.processId = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '设备工位',
                  value: udtTbWorkreportrecord.stationName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.stationName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '班组',
                  value: udtTbWorkreportrecord.teamName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.teamName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '生产车间',
                  value: udtTbWorkreportrecord.workshopName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.workshopName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 160,
                  label: '生产工厂',
                  value: udtTbWorkreportrecord.factoryName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.factoryName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
              ],
            ),
          ),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                Container(
                  width: 200,
                  padding: EdgeInsets.all(20),
                  child: TextFormField(
                    style: TextStyle(color: Colors.black),
                    decoration: InputDecoration(
                      labelText: '产品图号',
                      contentPadding: EdgeInsets.symmetric(horizontal: 10),
                    ),
                    controller: TextEditingController(
                        text: udtTbWorkreportrecord.productCode),
                    onSaved: (v) {
                      udtTbWorkreportrecord.productCode = v;
                    },
                    validator: (v) {
                      return v!.isEmpty ? S.of(context).required : null;
                    },
                  ),
                ),
                // Container(
                //   width: 250,
                //   padding: EdgeInsets.all(20),
                //   child: TextFormField(
                //     focusNode: _focusNode,
                //     style: TextStyle(color: Colors.black),
                //     decoration: InputDecoration(
                //       labelText: '生产单号',
                //       contentPadding: EdgeInsets.symmetric(horizontal: 10),
                //     ),
                //     controller: TextEditingController(text: udtTbWorkreportrecord.productionorderno),
                //     validator: (v) {
                //       return v!.isEmpty ? S.of(context).required : null;
                //     },
                //   ),),
                CryInput(
                  width: 160,
                  label: '报工人',
                  value: udtTbWorkreportrecord.reportworkerName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.reportworkerName = v;
                  },
                  // validator: (v) {
                  //   return v!.isEmpty ? S.of(context).required : null;
                  // },
                ),
                CryInput(
                  width: 200,
                  label: '产品名称',
                  value: udtTbWorkreportrecord.productName,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.productName = v;
                  },
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                ),
                CryInput(
                  width: 200,
                  label: '材料型号',
                  value: udtTbWorkreportrecord.spec,
                  enable: false,
                  onSaved: (v) {
                    udtTbWorkreportrecord.spec = v;
                  },
                  // validator: (v) {
                  //   return v!.isEmpty ? S.of(context).required : null;
                  // },
                ),
              ],
            ),
          ),
          SingleChildScrollView(scrollDirection: Axis.horizontal, child: table),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            if (dataList.length == 0) {
              CryUtils.message("请扫描单子");
              return;
            }
            if (isBlank(udtTbWorkreportrecord.reportworkerId)) {
              CryUtils.message("请扫描报工人");
              return;
            }
            form.save();
            udtTbWorkreportrecord.status = '0';
            udtTbWorkreportrecord.reportDate =
                DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
            // List saveData = dataList
            //     .map((e) {
            //       if(e.qualifiedquantity != 0){
            //         e.listToOdooMap(udtTbWorkreportrecord: udtTbWorkreportrecord);
            //       }
            //     }).toList();
            List saveData = [];
            dataList.forEach((element) {
              if (element.qualifiedquantity != 0){
                if(area != 0){
                  element.qualifiedquantity = element.qualifiedquantity! * area;
                }
                saveData.add(element.listToOdooMap(
                    udtTbWorkreportrecord: udtTbWorkreportrecord));
              }
            });
            UdtTbWorkreportrecordOdooApi.batchSave(saveData)
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              // Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
              _reset();
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: "返回",
          onPressed: () {
            Navigator.pop(context, true);
          },
          iconData: Icons.arrow_back,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return SizedBox.shrink();
          },
        ),
        title: Text("生产报工数据填报"),
        // actions: [ CryButton(
        //   label: "扫码",
        //   onPressed: () {
        //     _scan();
        //   },
        //   iconData: Icons.qr_code_scanner_outlined,
        // ) ] ,
      ),
      body: Column(
        children: [
          Expanded(
              child: SingleChildScrollView(
            child: form,
          )),
          // dataList.length != 0? SingleChildScrollView(
          //   scrollDirection:Axis.horizontal,
          //   child: Row(
          //     children: [
          //       Text("合计"),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.qualifiedquantity,
          //         onChange: (val) => _getTotal1(),
          //         onSaved: (v) {
          //           workreportrecord.qualifiedquantity = v;
          //         },
          //         // validator: (v) {
          //         //   return v!.isEmpty ? S.of(context).required : null;
          //         // }
          //       ),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.unqualifiedquantity,
          //         onSaved: (v) {
          //           workreportrecord.unqualifiedquantity = v;
          //         },
          //       ),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.repairquantity,
          //         onSaved: (v) {
          //           workreportrecord.repairquantity = v;
          //         },
          //       ),
          //       CryInputNum(
          //         width: 80,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.cutting,
          //         onSaved: (v) {
          //           workreportrecord.cutting = v;
          //         },
          //       ),
          //       CryInputNum(
          //         width: 150,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.replacenumber,
          //         onSaved: (v) {
          //           workreportrecord.replacenumber = v;
          //         },
          //       ),
          //       CryInput(
          //         width: 150,
          //         padding: 0,
          //         contentPadding: 0,
          //         value: workreportrecord.remark,
          //         onSaved: (v) {
          //           workreportrecord.remark = v;
          //         },
          //       ),
          //     ],
          //   ),
          // ):Container(),
        ],
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      // width: 700,
      height: 700,
      child: result,
    );
    // return result;
  }
}
